<script lang='ts' setup>
import { reactive, watch } from 'vue'
import { resources_save_file } from '@/apis/toolbox/resources/resources_save_file.ts'

const emits = defineEmits(['update:show', 'success', 'close'])

const props = defineProps({
  show: { required: true, type: Boolean },
  path: { required: true, type: String },
  name: {required: false, type: String, default: ''},
  content: {required: false, type: String, default: ''},
  readonly: {required: false, type: Boolean, default: false}
})

watch(props, async (): Promise<void> => {
  if ("" !== props.name!) {
    state.name = props.name!
    state.content = props.content!
  }
})

const state = reactive<{ name: string, content: string, saving: boolean }>({ name: '', content: '', saving: false })

async function close(): Promise<void> {
  state.name = ''
  state.content = ''
  emits('update:show', false)
}

async function save(): Promise<void> {
  if ("" === state.name.trim()) {
    window.$message.error("文件名称不能为空")

    return
  }

  state.saving = true
  const response = await resources_save_file(props.path! + state.name, state.content)
  state.saving = false

  if (0 !== response.code) {
    window.$message.error(response.message)

    return
  }

  window.$message.success("保存成功")
  await close()
  emits('success')
}
</script>

<template>
  <n-modal :closable='props.readonly!' :close-on-esc='props.readonly!' :mask-closable='props.readonly!' :show='props.show' class='resources-save-file-modal' transform-origin='center' @update:show='close'>
    <n-card>
      <n-space vertical>
        <n-divider>{{ props.readonly ? '查看' : '编辑' }}</n-divider>
        <div>
          <n-input-group>
            <n-input-group-label size='small'>文件名称</n-input-group-label>
            <n-input v-model:value='state.name' :disabled='props.readonly!' placeholder='文件名称，存在时覆盖，不存在则创建' size='small' />
          </n-input-group>
        </div>
        <div>
          <n-input v-model:value='state.content' :disabled='props.readonly!' rows='30' size='small' type='textarea' />
        </div>
        <div>
          <n-space align='center' justify='center'>
            <template v-if='!props.readonly!'>
              <n-button size='small' type='error' @click='close'>取消</n-button>
              <n-button :loading='state.saving' size='small' type='primary' @click='save'>保存</n-button>
            </template>
            <template v-else>
              <n-button size='small' type='primary' @click='emits("close"); close()'>关闭</n-button>
            </template>
          </n-space>
        </div>
      </n-space>
    </n-card>
  </n-modal>
</template>

<style scoped>
.resources-save-file-modal {
  width: 800px;
}
</style>
